package com.situ.mall.controller.back;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.io.FilenameUtils;
import org.apache.xmlbeans.impl.jam.mutable.MPackage;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.situ.mall.common.ServerResponse;
import com.situ.mall.util.ImageServerUtil;
import com.situ.mall.util.ImageServerUtil.EnumImageServer;
import com.situ.mall.util.QiniuUtil;

@Controller
@RequestMapping(value="/upload")
public class BackUploadController {

	@RequestMapping(value="/uploadImg")
	@ResponseBody
	public ServerResponse uploadImg(MultipartFile file) {//必须叫file
		String fileName = upload(file);
		return ServerResponse.createSuccess("成功", fileName);
	}

	private String upload(MultipartFile file) {
		if (ImageServerUtil.IMG_SERVER == EnumImageServer.QINIU) {
			try {
				return QiniuUtil.uploadImage(file.getBytes());
			} catch (IOException e) {
				e.printStackTrace();
			}
			return "";
		} else {// 上传到本地
			return uploadToLocal(file);
		}
	}
	
	private String uploadToLocal(MultipartFile file) {
		//为了防止文件重名（重名文件会被覆盖丢失），所以生成一个不重复的随机的名字
		//c11a85de-08a7-46ed-96ef-7227d28c5075
		//c11a85de08a746ed96ef7227d28c5075
		String name = UUID.randomUUID().toString().replace("-", "");
		//.jpg .png
		System.out.println(file.getOriginalFilename());// a.png
		// png
		String extension = FilenameUtils.getExtension(file.getOriginalFilename());
		// c11a85de08a746ed96ef7227d28c5075.png
		String fileName = name + "." +  extension;
		//把文件保存到d:\pic
		String filePath = "D:\\pic\\" + fileName;
		try {
			file.transferTo(new File(filePath));
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fileName;
	}

	@RequestMapping(value="/uploadImgByEditor")
	@ResponseBody
	public Map<String, Object> uploadImgByEditor(MultipartFile file) {
		String fileName = upload(file);
		
		//按照KindEditor的规则，返回它需要的数据
		String url = "/pic/" + fileName;
		Map<String, Object> map = new HashMap<>();
		map.put("error", 0);
		map.put("msg", "上传成功");
		map.put("url", url);
		return map;
	}
	
	public static void main(String[] args) {
		//03633eb591154ff59437aad6e4c8d81a
		String uuid = UUID.randomUUID().toString().replace("-", "");
		System.out.println(uuid);
	}
}
